﻿using System;
using System.Collections;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 字符串或集合或数组或字典不能为null或空, 示例:
/// <code>
/// [VNotNullOrEmpty]
/// public string Description { get; set; }
/// </code>
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VNotNullOrEmptyAttribute(string errorMessage = null) : Attribute, IValidateAction
{
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        if (ctx.StopValidate) return;
        if (ctx.ModelValue == null)
        {
            ctx.AddError(ctx.ModelName, ErrorMessage ?? $"'{ctx.ModelPath}' 不能为null!");
        }
        else if (ctx.ModelValue is IEnumerable list)
        {
            var idx = 0;
            foreach (var item in list)
            {
                idx++;
                break;
            }
            if (idx == 0)
            {
                ctx.AddError(ctx.ModelName, ErrorMessage ?? $"'{ctx.ModelPath}' 不能为空!");
            }
        }
    }
}
